<template>
	<view class="ys">
		<view class="chatlist">
			<scroll-view class="chatscroll" scroll-y :scroll-into-view="scrollView" scroll-with-animation="true"
				@scrolltoupper="toupper" @scrolltolower="tobottom" :refresher-enabled="allow_refresh"
				@refresherpulling="onpull" :refresher-triggered="triggered" @refresherrefresh="onrefresh"
				@refresherrestore="onstore" :refresher-threshold="40" refresher-background="#efefef">
				<view class="chatlength">
					<view class="more_text" v-show="allow_refresh">下拉加载更多</view>
					<view :class="item.say_type == 1?'chatitem mychat':'chatitem '" v-for="(item,index) in chatList"
						:key="index" :id="'tab'+item.id">
						<image class="headerimg" :src="item.head_url | getImg" mode=""></image>
						<view class="item-info">
							<view class="name">
								{{item.name}} <text>{{item.add_time}}</text>
							</view>
							<view class="item-msg" v-if="item.type == 1">
								<text>{{item.content}}</text>
							</view>
							<view class="item-imgbox" v-else-if="item.type == 2">
								<image :src="item.img_url | getImg" mode="widthFix" @click="bigImg(item.img_url)">
								</image>
							</view>
						</view>
					</view>
				</view>

			</scroll-view>
		</view>
		<view class="sendmsg">
			<view class="top">
				<view class="imgbox emo">
					<image @click="openEx" src="/static/bq.png" mode="widthFix"></image>
				</view>
				<textarea v-model="content" :style="minHeight" @linechange="changeLine" @focus="closeEx"></textarea>
				<view class="imgbox">
					<image v-show="content == ''" @click="uploadImg" src="/static/add.png" mode="widthFix"></image>
				</view>
				<text v-show="content != ''" @click="sendMsg">发送</text>
			</view>
			<view class="emoji">
				<emoKeyboard :show="show_ex" :data="data" @change="change" @delMsg="delMsg"></emoKeyboard>
			</view>
		</view>
	</view>
</template>

<script>
	// import {
	// 	room,
	// 	getChatList,
	// 	sendMsg
	// } from "@/api/user.js"
	import emoKeyboard from '@/components/emoji/emoKeyboard.vue';
	export default {
		data() {
			return {
				room_id: '',
				content: '',
				chatList: [],
				temp_list: [],
				img_url: '',
				img_url_show: '',
				scrollView: 'tab',
				user_id: '',
				triggered: false,
				_freshing: false,
				page: 0,
				total_page: 1,
				allow_refresh: true,
				is_init: true,
				last_id: '',
				minHeight: '',
				show_ex: false,
				data: [],
				is_connect: false
			}
		},
		components: {
			emoKeyboard
		},
		onUnload() {
			uni.onSocketClose(function(res) {
				console.log('WebSocket 已关闭！');
			});
		},
		onLoad(options) {
			if (options.room_id) {
				this.room_id = options.room_id
				this.room()
				setTimeout(() => {
					this.triggered = true;
				}, 1000)
			}
			this.webSocket()
			this.getData()
		},
		onNavigationBarButtonTap() {
			uni.navigateTo({
				url: './list?room_id=' + this.room_id
			})
		},
		methods: {
			change(emoji) {
				this.content += emoji
			},
			delMsg() { //删除
				if (!this.content) return
				const lastTwoChars = this.content.slice(-2);
				if (this.isEmoji(lastTwoChars)) {
					this.content = this.content.substring(0, this.content.length - 2);
				} else {
					this.content = this.content.substring(0, this.content.length - 1);
				}
			},
			isEmoji(str) {
				// 匹配表情的正则表达式
				const regExp = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
				return regExp.test(str);
			},
			getData() { //表情可以去这里复制https://geekerline.com/emoji/
				this.data = [
					"😀", "😃", "😄", "😁", "😆", "😅", "😂", "🤣", "😊", "😇", "🙂", "🙃", "😉", "😌", "😍", "🥰",
					"😘", "😗", "😙", "😚", "😋", "😛", "😝", "😜", "🤪", "🤨", "🧐", "🤓", "😎", "🤩", "🥳", "😏",
					"😒", "😞", "😔", "😟", "😕", "🙁", "😣", "😖", "😫", "😩", "🥺", "😢", "😭", "😤", "😠", "😡",
					"🤬", "🤯", "😳", "🥵", "🥶", "😱", "😨", "😰", "😥", "😓", "🤗", "🤔", "🤭", "🤫", "🤥", "😶",
					"😐", "😑", "😬", "🙄", "😯", "😦", "😧", "😮", "😲", "😴", "🤤", "😪", "😵", "🤐", "🥴", "🤢",
					"🤮", "🤧", "😷", "🤒", "🤕", "🤑", "🤠", "😈", "👿", "👹", "👺", "🤡", "💩", "👻", "💀", "☠",
					"👽", "👾", "🤖", "🎃", "😺", "😸", "😹", "😻", "😼", "😽", "🙀", "😿", "😾"
				];
			},
			closeEx() {
				this.show_ex = false
			},
			openEx() {
				this.show_ex = !this.show_ex
			},
			webSocket() {
				var that = this
				uni.connectSocket({
					// url: 'wss://www.example.com/socket',
					url: "ws://192.168.9.14:2348"
				});
				uni.onSocketOpen(function(res) {
					console.log('WebSocket连接已打开！');
					that.is_connect = true
				});
				uni.onSocketError(function(res) {
					console.log('WebSocket连接打开失败，请检查！');
				});
				uni.onSocketMessage(function(res) {
					let str = JSON.parse(res.data)
					console.log('收到服务器内容：', str);
				});
			},
			changeLine(e) {
				let height = e.detail.height
				if (height < 40) {
					this.minHeight = 'min-height:auto'
				} else if (height < 80) {
					this.minHeight = 'min-height:' + height + 'px'
				}
			},
			async room() {
				await room({
					room_id: this.room_id
				}).then(res => {
					console.log(res);
					uni.setNavigationBarTitle({
						title: res.data.studioInfo.studio_name + `(${res.data.room_count})`
					})
					this.user_id = res.data.user_id
				})
			},
			async getChatList() {
				let that = this
				await getChatList({
					room_id: this.room_id,
					page: this.page
				}).then(res => {

					that._freshing = false;
					this.temp_list = res.data.chat.data
					// this.chatList = [...res.data.chat.data, ...this.chatList]
					this.total_page = res.data.chat.last_page
					this.last_id = this.temp_list[this.temp_list.length - 1].id

				})
			},
			toupper(e) {
				console.log(e);
				setTimeout(() => {
					this.scrollView = 'tab' + this.chatList[0].id
					console.log(this.scrollView);
				}, 50)
			},
			tobottom(e) {
				console.log(e);
				// setTimeout(() => {
				// 	this.scrollView = 'tab' + this.chatList[this.chatList.length - 1].id
				// }, 50)
			},
			onpull(e) {
				// console.log('pull', e);
			},
			onrefresh(e) {
				let that = this
				console.log('fresh', e, that.triggered);
				if (that._freshing) return;
				that._freshing = true;
				that.page++;
				this.getChatList()
				setTimeout(() => {
					that.triggered = false;
					this.chatList = [...this.temp_list, ...this.chatList]
					if (this.page < this.total_page) {
						this.allow_refresh = true
					} else {
						this.allow_refresh = false
					}
					console.log('结束', that.triggered);
				}, 500)
				setTimeout(() => {
					if (this.is_init) {
						this.scrollView = 'tab' + this.last_id
					}
					console.log(this.scrollView);
				}, 800)
			},
			onstore(e) {
				this.triggered = 'restore'
				console.log('onstore', e);
			},
			more() {
				let more = []
				// let lenght = more.length
				// this.$nextTick(() => {
				// 	this.scrollView = 's' + lenght
				// })
				// console.log(this.scrollView);
				this.chatList = [...more, ...this.chatList]
			},
			getHeight() {
				setTimeout(() => {
					let info = uni.createSelectorQuery().select('.chatlength')
					info.boundingClientRect(function(data) { //data - 各种参数
						console.log(data.height);
						uni.pageScrollTo({
							scrollTop: data.height
						})
					}).exec()
				})
			},
			bigImg(url) {
				let base = getApp().globalData.data.websiteUrl
				let urls = [base + url]
				uni.previewImage({
					urls: urls
				})
			},
			sendSocketMessage(msg) {
				if (socketOpen) {
					uni.sendSocketMessage({
						data: msg
					});
				}
			},
			sendMsg() {
				if (!this.is_connect) {
					return uni.$showMsg('连接失败')
				}
				if (this.content == '' || this.content == undefined) {
					return false
				}
				var content = this.content
				uni.sendSocketMessage({
					data: content,
					success(res) {
						console.log(res);
					},
					fail(err) {
						console.log(err);
					}
				})
				return
				sendMsg({
					room_id: this.room_id,
					content: content,
				}).then(res => {
					if (res.status == 1) {
						this.chatList.push(res.data)
						setTimeout(() => {
							this.scrollView = 'tab' + res.data.id
						}, 100)
						// this.getHeight()
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
					}
				})

			},
			uploadImg() {
				let that = this
				uni.chooseImage({
					count: 1,
					success: (res) => {
						let imgurl = res.tempFilePaths[0]
						uni.uploadFile({
							//开发者服务器 url
							url: getApp().globalData.data.requestUrl + '/upload/chat',
							method: "POST",
							filePath: imgurl,
							fileType: 'image',
							name: 'image',
							header: {
								'token': uni.getStorageSync('token'),
								// 'Content-Type': 'application/x-www-form-urlencoded'  
							},
							formData: {
								room_id: that.room_id
							},
							success: (res) => {
								console.log(res)
								let info = JSON.parse(res.data)
								console.log(info);
								if (info.status == 1) {
									that.chatList.push(info.data)
									setTimeout(() => {
										that.scrollView = 'tab' + info.data.id
									}, 100)
								} else {
									uni.showToast({
										title: info.message,
										icon: 'none'
									})
								}

							}

						})
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: #efefef;
	}

	.more_text {
		text-align: center;
		margin-bottom: 16px;
		font-size: 12px
	}

	.more {
		text-align: center;
		padding-bottom: 10px;
	}

	.chatscroll {
		height: calc(100vh - 104px);
	}

	.sendmsg {
		position: fixed;
		width: 100%;
		background: #fff;
		min-height: 40px;
		bottom: 0;

		padding: 5px 0;
		box-sizing: border-box;
		line-height: 20px;

		.top {
			align-items: flex-end;
			display: flex;
			box-sizing: border-box;
			width: 100%;
			padding: 0 10px;
		}

		.emoji {
			width: 100%;
			background: #fff;
		}

		textarea {
			background: #efefef;
			flex: 1;
			padding: 8px;
			border-radius: 5px;
			max-height: 72px;
			height: auto;
			box-sizing: border-box;
		}

		.imgbox {
			height: 40px;
			display: flex;
			align-items: center;
		}

		image {
			width: 30px;
			margin-left: 10px;
			transition: .5;
		}

		.emo {
			image {
				margin-left: 0;
				margin-right: 10px;
			}
		}

		text {
			margin-left: 10px;
			background: #0a9413;
			color: #fff;
			height: 37px;
			width: 65px;
			display: flex;
			justify-content: center;
			align-items: center;
			box-sizing: border-box;
			border-radius: 5px;
			transition: .5;
		}
	}

	.chatlist {
		padding-top: 10px;
	}

	.chatitem {
		padding: 0 10px;
		margin-bottom: 15px;

		.headerimg {
			margin-top: 5px;
			width: 35px;
			height: 35px;
			border-radius: 5px;
			float: left;
		}

		.item-info {
			width: calc(90vw - 55px);
			padding-left: 10px;
			float: left;

			.name {
				color: #777;
				font-size: 12px;
				margin-bottom: 3px;

				text {
					margin-left: 5px;
				}
			}

			.item-msg {
				max-width: 100%;
				font-size: 14px;
				float: left;

				text {
					padding: 5px 10px;
					border-radius: 5px;
					background: #fff;
					display: block;
				}
			}

			.item-imgbox {
				image {
					max-width: 30%;
				}
			}
		}
	}

	.chatitem::after {
		content: '';
		display: block;
		height: 0;
		clear: both;
		visibility: hidden;
	}

	.mychat {
		.headerimg {
			float: right;
		}

		.item-info {
			float: right;
			padding-left: 0;
			padding-right: 10px;

			.name {
				text-align: right;
			}

			.item-msg {
				float: right;
			}

			.item-imgbox {
				text-align: right;
			}

		}
	}
</style>